package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMMatch;
import com.shwread.android.qysw.step.dto.HMMatchDto;
import com.shwread.android.qysw.step.dto.Player;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.RectImageView;
import com.shwread.android.qysw.tools.TimeHelper;
import com.shwread.android.qysw10000182.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/4/2.
 */
public class GroupPKDetailActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.game_start_time_text)
    TextView gameStartTimeText;
    @InjectView(R.id.owner_name_text)
    TextView ownerNameText;
    @InjectView(R.id.group_game_start_time_text)
    TextView groupGameStartTimeText;
    @InjectView(R.id.match_explain_text)
    TextView matchExplainText;
    @InjectView(R.id.mail_rank_text)
    TextView mailRankText;
    @InjectView(R.id.all_friends_list_layout)
    LinearLayout allFriendsListLayout;
    @InjectView(R.id.center_img)
    ImageView centerImg;
    @InjectView(R.id.goal_step_text)
    TextView goalStepText;
    @InjectView(R.id.goal_step_layout)
    LinearLayout goalStepLayout;
    @InjectView(R.id.show_more_description_text)
    TextView showMoreDescriptionText;
    @InjectView(R.id.game_person)
    TextView gamePerson;
    @InjectView(R.id.date_name)
    TextView dateName;
    @InjectView(R.id.game_shuoming)
    TextView gameShuoming;
    @InjectView(R.id.today_rank_text)
    TextView todayRankText;
    @InjectView(R.id.step_text)
    TextView stepText;
    @InjectView(R.id.score_text)
    TextView scoreText;
    @InjectView(R.id.current_layout)
    LinearLayout currentLayout;
    @InjectView(R.id.start_tag)
    TextView startTag;
    @InjectView(R.id.slh)
    TextView slh;
    @InjectView(R.id.no_result_text)
    TextView noResultText;
    @InjectView(R.id.no_result_layout)
    RelativeLayout noResultLayout;

    private int isNeedStep = 0;//0不需要,1需要

    boolean isFrompush;
    private HMMatch hmMatch;
    boolean mRes = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.group_pk_detail_activity);
        ButterKnife.inject(this);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        Intent intent = getIntent();
        isFrompush = intent.getBooleanExtra("push", false);
        isNeedStep = intent.getIntExtra("isNeedStep", 0);
        Log.i("darren", "FormPush:" + isFrompush);
        if (isFrompush) {
            String matchId = intent.getStringExtra("matchId");
            Log.i("darren", "matchId:" + matchId);
            HashMap<String, String> params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("matchId", matchId);
            String unstartUrl = "/hzlqswserver/health/game/getMatch";
            HashMap<String, String> hashMapUrl2 = new HashMap<>();
            hashMapUrl2.put("url", unstartUrl);
            MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");
                        HMMatchDto hmMatchDto = HMMatchDto.parserJson(res);
                        hmMatch = hmMatchDto.getHMMatch();
                        setView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
            asynctask.execute(hashMapUrl2, params);
        } else {
            hmMatch = (HMMatch) intent.getSerializableExtra("hMMatch");
            setView();
        }
    }

    private void setView() {
        titleText.setText(hmMatch.getLqswHealthMatch().getMatchName());
        if (isNeedStep == 1) {//竞赛
            gamePerson.setText("竞赛发起人:");
            dateName.setText("竞赛时间:");
            gameShuoming.setText("竞赛说明:");
            centerImg.setImageResource(R.drawable.h_goal_icon);
            goalStepLayout.setVisibility(View.VISIBLE);
            goalStepText.setText(hmMatch.getLqswHealthMatch().getTargetStep() + "步");
        } else {
            gamePerson.setText("团赛发起人:");
            dateName.setText("团赛时间:");
            gameShuoming.setText("团赛说明:");
            goalStepLayout.setVisibility(View.GONE);
            centerImg.setImageResource(R.drawable.h_group_pk_icon);
        }
//        if (hmMatch.getLqswHealthMatch().getMatchExplain().length() > 10) {
//            showMoreDescriptionText.setVisibility(View.VISIBLE);
//        } else {
//            showMoreDescriptionText.setVisibility(View.GONE);
//        }
        showMoreDescriptionText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (matchExplainText.getMaxLines() > 1) {
                    matchExplainText.setMaxLines(1);
                    slh.setVisibility(View.VISIBLE);
                } else {
                    slh.setVisibility(View.GONE);
                    matchExplainText.setMaxLines(8);
                }

            }
        });

        ownerNameText.setText(hmMatch.getLqswHealthMatch().getOwnerNickName());
        String betweenDate = TimeHelper.getMDate_M_DByTimeStamp(hmMatch.getLqswHealthMatch().getStartTime()) + "-" + TimeHelper.getMDate_M_DByTimeStamp(hmMatch.getLqswHealthMatch().getEndTime()) + TimeHelper.getDays(hmMatch.getLqswHealthMatch().getStartTime(), hmMatch.getLqswHealthMatch().getEndTime());
        groupGameStartTimeText.setText(betweenDate);
        matchExplainText.setText(hmMatch.getLqswHealthMatch().getMatchExplain());
        if (matchExplainText.getLineCount() > 1) {
            slh.setVisibility(View.VISIBLE);
            showMoreDescriptionText.setVisibility(View.VISIBLE);
        } else {
            slh.setVisibility(View.GONE);
            showMoreDescriptionText.setVisibility(View.GONE);
        }
        if (hmMatch.getLqswHealthMatch().getState() == 1) {
            startTag.setText("距离比赛开始还剩");
            gameStartTimeText.setText(TimeHelper.getMyCountDownTime(hmMatch.getLqswHealthMatch().getStartTime()));
            mailRankText.setVisibility(View.GONE);
            for (int i = 0; i < hmMatch.getPlayers().size(); i++) {
                Player player = hmMatch.getPlayers().get(i);
                View view = View.inflate(this, R.layout.healthy_other_user_grade_item, null);
                TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                numTextView.setText(player.getSort() + "");
                RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                if (!TextUtils.isEmpty(player.getUserHead())) {
                    Picasso.with(this).load(player.getUserHead()).into(headIconImg);
                }
                TextView nameText = (TextView) view.findViewById(R.id.name_text);
                nameText.setText(player.getNickName());
                final TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                if (player.getIsAccept() == 1) {
                    stepCountText.setText("已接受");
                    stepCountText.setTextColor(getResources().getColor(R.color.blue_25));
                    if (hmMatch.getLqswHealthMatch().getOwnerId() == player.getUserId()) {
                        stepCountText.setText("发起者");
                    }
                } else {
                    if (player.getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                        stepCountText.setText("接受");
                        stepCountText.setTextColor(GroupPKDetailActivity.this.getResources().getColor(R.color.white));
                        final ImageView imageView = (ImageView) view.findViewById(R.id.accept_button);
                        imageView.setBackgroundColor(getResources().getColor(R.color.blue_25));
                        imageView.setVisibility(View.VISIBLE);
                        imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                HashMap<String, String> params = new HashMap<>();
                                params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                                params.put("enterpriseId", AppConfig.getEnterpriseId());
                                params.put("matchId", hmMatch.getLqswHealthMatch().getMatchId() + "");

                                String unstartUrl = "hzlqswserver/health/game/accept";
                                HashMap<String, String> hashMapUrl2 = new HashMap<>();
                                hashMapUrl2.put("url", unstartUrl);
                                MyAsynctask asynctask = new MyAsynctask(GroupPKDetailActivity.this, new MyAsynctask.RequestListener() {
                                    @Override
                                    public void requestSuccess(String result) {
                                        JSONObject jsonObject = null;
                                        try {
                                            jsonObject = new JSONObject(result);
                                            String res = jsonObject.optString("resultCode");
                                            if ("1000".equals(res)) {
                                                Toast.makeText(GroupPKDetailActivity.this, "接受成功", Toast.LENGTH_LONG).show();
                                                mRes = true;
                                                imageView.setVisibility(View.GONE);
                                                stepCountText.setText("已接受");
                                                stepCountText.setTextColor(getResources().getColor(R.color.blue_25));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                                asynctask.execute(hashMapUrl2, params);
                            }
                        });
                    } else {
                        stepCountText.setText("未接受");
                    }
                }
                allFriendsListLayout.addView(view);
            }
        } else {
            if (hmMatch.getLqswHealthMatch().getState() == 2) {
                todayRankText.setText("今日战绩排行榜");
                startTag.setText("距离比赛结束还剩");
                gameStartTimeText.setText(TimeHelper.getMyCountDownTime(hmMatch.getLqswHealthMatch().getEndTime()));
            }
            if (hmMatch.getLqswHealthMatch().getState() == 3) {
                todayRankText.setText("战绩总排名");
            }
            if (hmMatch.getLqswHealthMatch().getState() == 4) {
                noResultLayout.setVisibility(View.VISIBLE);
                mailRankText.setVisibility(View.GONE);
                allFriendsListLayout.setVisibility(View.VISIBLE);
                currentLayout.setVisibility(View.GONE);
                if (isNeedStep == 1) {
                    noResultText.setText("竞赛失效,不能加入比赛");
                    centerImg.setImageResource(R.drawable.score_game_no);
                } else {
                    noResultText.setText("团赛失效,不能加入比赛");
                    centerImg.setImageResource(R.drawable.group_game_no);
                }
                for (int i = 0; i < hmMatch.getPlayers().size(); i++) {
                    Player player = hmMatch.getPlayers().get(i);
                    View view = View.inflate(this, R.layout.healthy_other_user_grade_item, null);
                    TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                    numTextView.setText(player.getSort() + "");
                    RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                    if (!TextUtils.isEmpty(player.getUserHead())) {
                        Picasso.with(this).load(player.getUserHead()).into(headIconImg);
                    }
                    TextView nameText = (TextView) view.findViewById(R.id.name_text);
                    nameText.setText(player.getNickName());
                    final TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                    if (player.getIsAccept() == 1) {
                        stepCountText.setText("已接受");
                        stepCountText.setTextColor(getResources().getColor(R.color.blue_25));
                        if (hmMatch.getLqswHealthMatch().getOwnerId() == player.getUserId()) {
                            stepCountText.setText("发起者");
                        }
                    } else {
                        if (player.getUserId() == UserHealthyModel.getInstance().getMyHmUserInfo().getUserId()) {
                            stepCountText.setText("接受");
                            stepCountText.setTextColor(GroupPKDetailActivity.this.getResources().getColor(R.color.white));
                            final ImageView imageView = (ImageView) view.findViewById(R.id.accept_button);
                            imageView.setVisibility(View.VISIBLE);
                            imageView.setBackgroundColor(getResources().getColor(R.color.gray_97));
                        } else {
                            stepCountText.setText("未接受");
                        }
                    }
                    allFriendsListLayout.addView(view);
                }
            } else {
                if (isNeedStep == 1) {
                    mailRankText.setVisibility(View.GONE);
                    currentLayout.setVisibility(View.VISIBLE);
                    for (int i = 0; i < hmMatch.getPlayers().size(); i++) {
                        Player player = hmMatch.getPlayers().get(i);
                        View view = View.inflate(this, R.layout.h_other_pk_score_item, null);
                        TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                        numTextView.setText(player.getSort() + "");
                        RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                        if (!TextUtils.isEmpty(player.getUserHead())) {
                            Picasso.with(this).load(player.getUserHead()).into(headIconImg);
                        }
                        TextView nameText = (TextView) view.findViewById(R.id.name_text);
                        nameText.setText(player.getNickName());
                        TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                        stepCountText.setText(player.getStep() + "");
                        TextView totalScoreText = (TextView) view.findViewById(R.id.total_score_text);
                        totalScoreText.setText(player.getTotalScore() + "分");
                        allFriendsListLayout.addView(view);
                    }
                } else {
                    mailRankText.setVisibility(View.VISIBLE);
                    if (hmMatch.getLqswHealthMatch().getState() == 2) {
                        mailRankText.setText("比赛排行");
                    } else if (hmMatch.getLqswHealthMatch().getState() == 3) {
                        mailRankText.setText("总排行");
                    }
                    for (int i = 0; i < hmMatch.getPlayers().size(); i++) {
                        Player player = hmMatch.getPlayers().get(i);
                        View view = View.inflate(this, R.layout.healthy_other_user_grade_item, null);
                        TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                        numTextView.setText(player.getSort() + "");
                        RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                        if (!TextUtils.isEmpty(player.getUserHead())) {
                            Picasso.with(this).load(player.getUserHead()).into(headIconImg);
                        }
                        TextView nameText = (TextView) view.findViewById(R.id.name_text);
                        nameText.setText(player.getNickName());
                        TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                        stepCountText.setText(player.getStep() + "");
                        allFriendsListLayout.addView(view);
                    }
                }
            }


        }
    }

    public boolean acceptGame() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        params.put("matchId", hmMatch.getLqswHealthMatch().getMatchId() + "");

        String unstartUrl = "hzlqswserver/health/game/accept";
        HashMap<String, String> hashMapUrl2 = new HashMap<>();
        hashMapUrl2.put("url", unstartUrl);
        MyAsynctask asynctask = new MyAsynctask(GroupPKDetailActivity.this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("resultCode");
                    if ("1000".equals(res)) {
                        Toast.makeText(GroupPKDetailActivity.this, "接受成功", Toast.LENGTH_LONG).show();
                        mRes = true;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        asynctask.execute(hashMapUrl2, params);
        return mRes;
    }
}
